package com.sczmgk.track.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.baidu.mapapi.model.LatLng;
import com.sczmgk.track.MyApp;
import com.sczmgk.track.constant.Constant;
import com.sczmgk.track.entity.CurrentLocation;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@SuppressLint("ShowToast")
public class CommonUtils {

    private static final String TAG = CommonUtils.class.getSimpleName();

    public static final double DISTANCE = 0.0001;

    private static DecimalFormat df = new DecimalFormat("######0.00");

    /**
     * 取得手机的Imei
     *
     * @param context
     * @return 返回手机的串号
     */
    public static String getPhoneImei(Context context) {
        String imei = ((TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE)).getDeviceId();
        return imei.toString();
    }

    /**
     * 取得WifiMAC地址，没开wifi都能得到
     *
     * @param context
     * @return 返回手机WIFI MAC地址
     */
    @SuppressLint("ServiceCast")
    public static String getWifiMac(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /**
     * 取得屏幕像素密度
     *
     * @param context
     * @return
     */
    public static float getScreenDensity(Context context) {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            WindowManager manager = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            manager.getDefaultDisplay().getMetrics(dm);
            return dm.density;
        } catch (Exception ex) {

        }
        return 1.0f;
    }

    // private static AlertDialog alertDialog = null;

    public static final int MSG_SHOW_ALERTDIALOG = 1;

    private static List<Activity> activityList = new ArrayList<Activity>();

    /**
     * 转出
     */
    public static final String IP_FLAG_REC = "0";
    /**
     * 转入
     */
    public static final String IP_FLAG_PAY = "1";

    public static final String SHARED_CONFIG_FILE_NAME = "shared_config";

    /**
     * 判断网络是否畅通
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 判断网络是否畅通
     *
     * @param context
     * @return
     */
    public static boolean isWifiNetwork(Context context) {
        boolean is3GNetwork = false;
        ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connec.getActiveNetworkInfo();
        if (info == null) {
            return false;
        }
        int localNetworkType = info.getType();
        is3GNetwork = ConnectivityManager.TYPE_WIFI == localNetworkType;

        return is3GNetwork;
    }

    /**
     * 移除Activity
     *
     * @param activity
     */
    public static void removeActivity(Activity activity) {
        activityList.remove(activity);
    }

    /**
     * 添加Activity
     *
     * @param activity
     */
    public static void addActivity(Activity activity) {
        activityList.add(activity);
    }

    /**
     * 取得在前台的Activity集合
     *
     * @return
     */
    public static List<Activity> getActivityList() {
        return activityList;
    }

    /**
     * 结束Activity
     */
    public static void finishActivity() {
        for (Activity activity : activityList) {
            activity.finish();
        }
    }

    /**
     * 字符串非空判断
     *
     * @param s 字符串
     */
    public static boolean StringIsNull(String s) {
        boolean result = false;
        if (null == s || "".equals(s.trim())) {
            result = true;
        }
        return result;
    }

    /**
     * json解析后空字符窜 变成 null，此方法将null字符串 变成空
     *
     * @param s 字符串
     */
    public static boolean StringReplaceNull(String s) {
        if (StringIsNull(s) || s.equals("null")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断字符串为不为null？字符串：deVanul
     *
     * @param s 字符串
     */
    public static String getStringFilteNull(String s, String deValue) {
        return StringReplaceNull(s) ? deValue : s;
    }

    /**
     * Retrieves application's version number from the manifest 版本代码
     *
     * @return Version
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;

        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return versionCode;
    }

    /**
     * Retrieves application's version name from the manifest 版本
     *
     * @return Version
     */
    public static String getVersionName(Context context) {
        String versionName = null;
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return versionName;
    }


    /**
     * @param s
     * @param i
     */
    static void pBinInt(String s, int i) {
        System.out.println(s + ", int: " + i + ", binary: ");
        System.out.print("   ");
        for (int j = 31; j >= 0; j--)
            if (((1 << j) & i) != 0)
                System.out.print("1");
            else
                System.out.print("0");
        System.out.println();
    }


    /**
     * 隐藏软键盘
     */
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);// 隐藏软键盘
        }
    }


    /**
     * 根据jid获取username
     *
     * @return
     */
    public static String getUsernameByJid(String jid) {
        if (Tools.isEmpty(jid)) {
            return "";
        } else {
            if (jid.contains("@")) {
                return jid.substring(0, jid.indexOf("@"));
            } else {
                return jid;
            }
        }
    }

    /**
     * 获取系统的版本
     */
    public static int getSDKVersionValue() {
        return android.os.Build.VERSION.SDK_INT;
    }

    /**
     * 标点半角转为全角
     *
     * @param input 要转的字符串
     * @return 转成功后的字符串
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }


    /**
     * 程序是否在前台运行 * * @return
     */
    public static boolean isAppOnForeground(Context context) {
        // Returns a list of application processes that are running on the
        // device
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(
                Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;

    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        return simpleDateFormat.format(date);
    }

    public static String InputStreamTOString(InputStream in, String encoding) throws Exception {

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int count = -1;
        while ((count = in.read(data, 0, 1024)) != -1)
            outStream.write(data, 0, count);

        data = null;
        return new String(outStream.toByteArray(), encoding);
    }

    /**
     * 加密session key
     *
     * @param friendSession
     * @return
     */
    public static String buildSessionKey(String friendSession) {
        if (friendSession == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder(friendSession);
        String fMsg = friendSession + sb.reverse();

        while (fMsg.length() < 24 * 2) {
            fMsg += fMsg;
        }

        StringBuilder fsb = new StringBuilder();
        for (int i = 0; i < 48; i += 2) {
            fsb.append(fMsg.charAt(i));
        }
        return fsb.toString();
    }

    /**
     * 拨打电话
     *
     * @param context
     * @param phoneNumber
     */
    public static void callPhone(final Context context, final String phoneNumber) {
        Activity activity = (Activity) context;

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + phoneNumber));
                context.startActivity(intent);
            }
        });
    }


    /**
     * 获取版本号
     *
     * @return
     */

    private static String getAndroidVersion() {

        String result = "";
        try {
            //Android 版本号  如: 5.1.1
            String version = android.os.Build.VERSION.RELEASE;
            result = "Android" + version;
            return result;
        } catch (Exception e) {
            return result;
        }

    }

    /**
     * 获取App版本号
     *
     * @param context
     * @return
     */
    public static int getAppVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    private static String getBuildModel() {
        String result = "";
        try {
            //手机型号
            result = android.os.Build.MODEL;
            return result;
        } catch (Exception e) {
            return result;
        }
    }

    /**
     * 保留小数点后两位小数
     *
     * @param editText
     */
    public static void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

    }

    public static void reportImei(final Context context) {
        Map<String, Object> maps = new HashMap<String, Object>();
        //TODO userid
        maps.put("userid", "");
        maps.put("lastusetime", "");
        maps.put("imei", MyApp.imei);
        maps.put("osplatform", getAndroidVersion());
        maps.put("osversion", getBuildModel());
        //TODO 上报imei
//        MyHttp.request(context, Constant.POST_UPLOAD_IMEI, maps, MyHttp.POST, false, null, new SimplePaserJsonCallback() {
//            @Override
//            public void onVerifyIsNull() {
//
//            }
//
//            @Override
//            public void onVerifySuccess(String dataRaw) {
//
//            }
//
//            @Override
//            public void onServerUnKnownError() {
//
//            }
//
//            @Override
//            public void onErrorCodeError(String msg) {
//
//            }
//        });
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return "";
    }

    /**
     * 获取当前时间戳(单位：秒)
     *
     * @return
     */
    public static long getCurrentTime() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 校验double数值是否为0
     *
     * @param value
     * @return
     */
    public static boolean isEqualToZero(double value) {
        return Math.abs(value - 0.0) < 0.01 ? true : false;
    }

    /**
     * 经纬度是否为(0,0)点
     *
     * @return
     */
    public static boolean isZeroPoint(double latitude, double longitude) {
        return isEqualToZero(latitude) && isEqualToZero(longitude);
    }

    /**
     * 将字符串转为时间戳
     */
    public static long toTimeStamp(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA);
        Date date;
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
        return date.getTime() / 1000;
    }

    /**
     * 获取时分秒
     *
     * @param timestamp 时间戳（单位：毫秒）
     * @return
     */
    public static String getHMS(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try {
            return sdf.format(new Timestamp(timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(timestamp);
    }

    /**
     * 获取年月日 时分秒
     *
     * @param timestamp 时间戳（单位：毫秒）
     * @return
     */
    public static String formatTime(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.format(new Timestamp(timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(timestamp);
    }

    public static String formatSecond(int second) {
        String format = "%1$,02d:%2$,02d:%3$,02d";
        Integer hours = second / (60 * 60);
        Integer minutes = second / 60 - hours * 60;
        Integer seconds = second - minutes * 60 - hours * 60 * 60;
        Object[] array = new Object[]{hours, minutes, seconds};
        return String.format(format, array);
    }

    public static final String formatDouble(double doubleValue) {
        return df.format(doubleValue);
    }

    /**
     * 计算x方向每次移动的距离
     */
    public static double getXMoveDistance(double slope) {
        if (slope == Double.MAX_VALUE) {
            return DISTANCE;
        }
        return Math.abs((DISTANCE * slope) / Math.sqrt(1 + slope * slope));
    }

    /**
     * 根据点和斜率算取截距
     */
    public static double getInterception(double slope, LatLng point) {
        return point.latitude - slope * point.longitude;
    }

    /**
     * 算斜率
     */
    public static double getSlope(LatLng fromPoint, LatLng toPoint) {
        if (toPoint.longitude == fromPoint.longitude) {
            return Double.MAX_VALUE;
        }
        return (toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude);
    }

    /**
     * 根据两点算取图标转的角度
     */
    public static double getAngle(LatLng fromPoint, LatLng toPoint) {
        double slope = getSlope(fromPoint, toPoint);
        if (slope == Double.MAX_VALUE) {
            if (toPoint.latitude > fromPoint.latitude) {
                return 0;
            } else {
                return 180;
            }
        }
        float deltAngle = 0;
        if ((toPoint.latitude - fromPoint.latitude) * slope < 0) {
            deltAngle = 180;
        }
        double radio = Math.atan(slope);
        return 180 * (radio / Math.PI) + deltAngle - 90;
    }

    /**
     * 保存当前定位点
     */
    public static void saveCurrentLocation(MyApp trackApp) {
        SharedPreferences.Editor editor = trackApp.trackConf.edit();
        StringBuffer locationInfo = new StringBuffer();
        locationInfo.append(CurrentLocation.locTime);
        locationInfo.append(";");
        locationInfo.append(CurrentLocation.latitude);
        locationInfo.append(";");
        locationInfo.append(CurrentLocation.longitude);
        editor.putString(Constant.LAST_LOCATION, locationInfo.toString());
        editor.apply();
    }

}
